package cn.hznc.controller.service.process;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.constant.CommonConstant;
import cn.hznc.constant.SortTaskEnum;
import cn.hznc.constant.WarehouseConstant;
import cn.hznc.controller.service.QuerySqlServerService;
import cn.hznc.controller.service.process.logic.ProcessBomDo;
import cn.hznc.controller.service.process.logic.ProcessCraftLogic;
import cn.hznc.controller.service.production.ProductionManageService;
import cn.hznc.domain.entity.*;
import cn.hznc.domain.request.order.EditCraftTaskReq;
import cn.hznc.domain.request.process.*;
import cn.hznc.domain.request.production.PucAndProConnectReq;
import cn.hznc.domain.request.schedule.MachineToolChildReq;
import cn.hznc.domain.response.PageResult;
import cn.hznc.dto.AllotEmployeeImport;
import cn.hznc.exception.ToolManageEx;
import cn.hznc.exception.ToolManageException;

import cn.hznc.mapper.*;
import cn.hznc.repository.*;
import cn.hznc.controller.service.process.logic.ProcessCraftDo;
import cn.hznc.utils.CommonUtil;
import cn.hznc.utils.UUIDUtil;
import cn.hznc.vo.*;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Author Administrator
 * @Date 2023/3/15 10:46
 */
@Service
public class ProcessManageService {

    @Resource
    private ProcessMapper processMapper;

    @Resource
    private ProcessCraftMapper processCraftMapper;

    @Resource
    private ProcessBomMapper processBomMapper;


    @Resource
    private WarehouseRespository warehouseRespository;

    @Resource
    private SubProgramRespository subProgramRespository;

    @Resource
    private ProductionProcessMapper productionProcessMapper;

    @Resource
    private MachineToolTaskMapper machineToolTaskMapper;

    @Resource
    private MachineToolTaskRespository machineToolTaskRespository;

    @Resource
    private ProcessRepository processRepository;

    @Resource
    private OrderCraftMapper orderCraftMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ProductionMapper productionMapper;

    @Resource
    private EmployeeMachineToolConnectMapper employeeMachineToolConnectMapper;
    @Resource
    private ProductionManageService productionManageService;

    @Resource
    private ProductionRespository productionRespository;

    @Resource
    private ProcessCraftProgramRepository processCraftProgramRepository;

    @Resource
    private QuerySqlServerService querySqlServerService;
    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private EquipmentGroupRepository equipmentGroupRepository;

    @Resource
    private AllotEmployeeRepository allotEmployeeRepository;

    @Resource
    private AllotEmployeeMapper allotEmployeeMapper;

    @Resource
    private MachineToolStatusRepository machineToolStatusHistoryRepository;

    @Resource
    private MachineToolProgramMapper machineToolProgramMapper;


    private static final HashMap<String, String> sortEnumMap = new HashMap<>();

    static {
        sortEnumMap.put("startTime" , "StartTime");
    }
    /**
     * 分页查询工序
     *
     * @param queryProcessReq queryProcessReq
     * @return
     */
    public PageResult<ProcessEntity> queryProcessList(QueryProcessReq queryProcessReq) {
        PageHelper.startPage(queryProcessReq.getPageNum(), queryProcessReq.getPageSize());
        LambdaQueryWrapper<ProcessEntity> wrapper = buildQueryWrapper(queryProcessReq);
        PageInfo<ProcessEntity> pageInfo = new PageInfo<>(processMapper.selectList(wrapper));
        //构建图号查询条件
        List<ProcessEntity> filterList = filterByFigureNo(pageInfo.getList(), queryProcessReq.getMaterialNo());
        //List<Integer> 
//        filterList.forEach(processEntity -> {
//            ProductionEntity productionEntity = processRepository.selectProductionByProcessCode(processEntity.getCode());
//            if (ObjectUtil.isNotNull(productionEntity)) {
//                processEntity.setProductionName(productionEntity.getName());
//                processEntity.setMaterialNo(productionEntity.getMaterialNo());
//            }
//        });
        //设置工艺关联产品信息
        filterList.forEach(processEntity -> {
            List<String> materialNos = processRepository.selectFigureNoByCode(processEntity.getCode());
            if (CollectionUtil.isNotEmpty(materialNos)) {
                processEntity.setChild(productionRespository.selectByFigureNo(materialNos));
            }
        });
        return new PageResult<>(filterList, pageInfo.getTotal());
    }

    private List<ProcessEntity> filterByFigureNo(List<ProcessEntity> list, String materialNo) {
        if (StringUtils.isEmpty(materialNo)) {
            return list;
        }
        String code = processRepository.selectCodeByFigureNo(materialNo);
        if (StringUtils.isNotEmpty(code)) {
            return list.stream()
                    .filter(processEntity -> code.equals(processEntity.getCode()))
                    .collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    private LambdaQueryWrapper<ProcessEntity> buildQueryWrapper(QueryProcessReq queryProcessReq) {
        LambdaQueryWrapper<ProcessEntity> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(queryProcessReq.getName())) {
            wrapper.like(ProcessEntity::getName, queryProcessReq.getName());
        }
        if (StringUtils.isNotEmpty(queryProcessReq.getProcessNum())) {
            wrapper.like(ProcessEntity::getProcessNum, queryProcessReq.getProcessNum());
        }
        if (StringUtils.isNotEmpty(queryProcessReq.getType())) {
            wrapper.eq(ProcessEntity::getProcessType, queryProcessReq.getType());
        }
        if (ObjectUtil.isNotNull(queryProcessReq.getStatus())) {
            wrapper.eq(ProcessEntity::getStatus, queryProcessReq.getStatus());
        }
        return wrapper;
    }

    /**
     * 编辑和修改
     *
     * @param addOrEditProcessReq addOrEditProcessReq
     * @return
     */
    @Transactional
    public Boolean addOrEditProcess(AddOrEditProcessReq addOrEditProcessReq) throws ToolManageException {
        // 校验-1.校验图号是否为空
//        if (StringUtils.isEmpty(addOrEditProcessReq.getFigureNo())) {
//            throw new ToolManageException(ToolManageEx.PROCESS_FIGURE_NUMBER_IS_NULL.getCode(), ToolManageEx.PROCESS_FIGURE_NUMBER_IS_NULL.getMsg());
//        }
        // 校验-2.校验图号是否唯一
//        List<ProcessEntity> list = processMapper.selectList(buildQueryWrapper(addOrEditProcessReq));
//        if (!CheckUtil.isUniqe(addOrEditProcessReq.getId(), list)) {
//            throw new ToolManageException(ToolManageEx.PROCESS_FIGURE_NUMBER_REPEAT.getCode(), ToolManageEx.PROCESS_FIGURE_NUMBER_REPEAT.getMsg());
//        }
        ProcessEntity processEntity = new ProcessEntity();
        BeanUtil.copyProperties(addOrEditProcessReq, processEntity);
        if (Objects.isNull(processEntity.getId())) {
            //校验工艺编码唯一性
            checkProcessNum(addOrEditProcessReq.getProcessNum());
            // 新增
            processEntity.setCreateTime(new Date());
            processEntity.setVersion(CommonConstant.INIT_VERSION);
            processEntity.setCode("process-" + UUIDUtil.getUUID());
            processEntity.setStatus(CommonConstant.PROCESS_NOT_DONE);
            processMapper.insert(processEntity);
        } else {
            // 修改
            ProcessEntity existProcess = processMapper.selectById(addOrEditProcessReq.getId());
            if (StringUtils.isNotEmpty(existProcess.getProcessNum())) {
                ProductionEntity productionEntity = productionManageService.getProductionEntity(existProcess.getProcessNum());
                if (ObjectUtil.isNotNull(productionEntity)) {
                    productionEntity.setProductionProcessConnectStatus(CommonConstant.PRODUCTION_PROCESS_NOT_CONNECT);
                    productionManageService.setProductionStatus(productionEntity);
                }
            }
            processEntity.setUpdateTime(new Date());
            processMapper.updateById(processEntity);

        }
        //关联产品和工艺
        return Boolean.TRUE;

    }


    private LambdaQueryWrapper<ProcessEntity> buildQueryWrapper(AddOrEditProcessReq addOrEditProcessReq) {
        LambdaQueryWrapper<ProcessEntity> wrapper = new LambdaQueryWrapper<>();
        if (Objects.isNull(addOrEditProcessReq.getVersion())) {
            addOrEditProcessReq.setVersion(CommonConstant.INIT_VERSION);
        }
        wrapper.eq(ProcessEntity::getFigureNo, addOrEditProcessReq.getFigureNo())
                .eq(ProcessEntity::getVersion, addOrEditProcessReq.getVersion());
        return wrapper;
    }

    private void checkProcessNum(String processNum) throws ToolManageException {
        LambdaQueryWrapper<ProcessEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProcessEntity::getProcessNum, processNum);
        ProcessEntity processEntity = processMapper.selectOne(wrapper);
        if (ObjectUtil.isNotNull(processEntity)) {
            throw new ToolManageException(ToolManageEx.PROCESS_NUM_REPEAT.getCode(), ToolManageEx.PROCESS_NUM_REPEAT.getMsg());
        }
    }

    /**
     * 删除工序
     *
     * @param deleteProcessReq deleteProcessReq
     * @return
     */
    public Boolean deleteProcess(DeleteProcessReq deleteProcessReq) {
        if (StringUtils.isEmpty(deleteProcessReq.getProcessCode())) {
            return Boolean.TRUE;
        }
        // 先删除关联的工艺
        LambdaQueryWrapper<ProcessCraftEntity> deleteCraftWrapper = new LambdaQueryWrapper<>();
        deleteCraftWrapper.eq(ProcessCraftEntity::getProcessCode, deleteProcessReq.getProcessCode());
        processCraftMapper.delete(deleteCraftWrapper);
        // 再删除关联的物料
        LambdaQueryWrapper<ProcessBomEntity> deleteBomWrapper = new LambdaQueryWrapper<>();
        deleteBomWrapper.eq(ProcessBomEntity::getProcessCode, deleteProcessReq.getProcessCode());
        processBomMapper.delete(deleteBomWrapper);
        // 最后删除关联的工序
        LambdaQueryWrapper<ProcessEntity> deleteProcessWrapper = new LambdaQueryWrapper<>();
        deleteProcessWrapper.eq(ProcessEntity::getCode, deleteProcessReq.getProcessCode());
        processMapper.delete(deleteProcessWrapper);
        return Boolean.TRUE;
    }


    /**
     * 查询工艺详情
     *
     * @param queryCraftDetailReq queryCraftDetailReq
     * @return
     */
    public List<ProcessCraftEntity> queryCraftDetail(QueryCraftDetailReq queryCraftDetailReq) {
        LambdaQueryWrapper<ProcessCraftEntity> wrapper = buildQueryWrapper(queryCraftDetailReq.getProcessCode(), queryCraftDetailReq.getVersion());
        return processCraftMapper.selectList(wrapper);
    }


    private LambdaQueryWrapper<ProcessCraftEntity> buildQueryWrapper(String processCode, Integer version) {
        LambdaQueryWrapper<ProcessCraftEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(ProcessCraftEntity::getSeq);
        wrapper.eq(ProcessCraftEntity::getProcessCode, processCode);
        wrapper.eq(ProcessCraftEntity::getVersion, version);
        return wrapper;
    }

//    /**
//     * 查询物料详情
//     *
//     * @param queryBomDetailReq queryBomDetailReq
//     * @return
//     */
//    public List<ProcessBomEntity> queryBomDetail(QueryBomDetailReq queryBomDetailReq) {
//        LambdaQueryWrapper<ProcessBomEntity> wrapper = buildQueryWrapper(queryBomDetailReq);
//        return processBomMapper.selectList(wrapper);
//    }
//
//    private LambdaQueryWrapper<ProcessBomEntity> buildQueryWrapper(QueryBomDetailReq queryBomDetailReq) {
//        LambdaQueryWrapper<ProcessBomEntity> wrapper = new LambdaQueryWrapper<>();
//        wrapper.orderByAsc(ProcessBomEntity::getSeq);
//        wrapper.eq(ProcessBomEntity::getFigureNo, queryBomDetailReq.getFigureNo());
//        wrapper.eq(ProcessBomEntity::getVersion, queryBomDetailReq.getVersion());
//        return wrapper;
//    }

    /**
     * 编辑工艺流程
     *
     * @param operateCraftReq operateCraftReq
     * @return
     * @throws ToolManageException
     */
    public Boolean editOrAddCraft(OperateCraftReq operateCraftReq) throws ToolManageException {
        if (StringUtils.isEmpty(operateCraftReq.getProcessCode())) {
            throw new ToolManageException(ToolManageEx.PROCESS_CRAFT_CONNECT_ERROR.getCode(), ToolManageEx.PROCESS_CRAFT_CONNECT_ERROR.getMsg());
        }
        LambdaQueryWrapper<ProcessCraftEntity> wrapper = buildProcessCraftWrapper(operateCraftReq.getProcessCode(), operateCraftReq.getVersion());
        List<ProcessCraftEntity> originProcessCraftList = processCraftMapper.selectList(wrapper);
        List<ProcessCraftEntity> updateProcessCraftList = transferProcessCraft(operateCraftReq);
        ProcessCraftLogic processCraftLogic = new ProcessCraftLogic(originProcessCraftList, updateProcessCraftList);

        processCraftLogic.buildProcessCraftDo();
        ProcessCraftDo processCraftDo = processCraftLogic.getProcessCraftDo();
        // 持久化
        persistCraft(processCraftDo);

        return Boolean.TRUE;
    }


    private List<ProcessCraftEntity> transferProcessCraft(OperateCraftReq operateCraftReq) {
        if (CollectionUtil.isEmpty(operateCraftReq.getBatchCraftReq())) {
            return Collections.emptyList();
        }
        List<ProcessCraftEntity> updateProcessCraftList = new ArrayList<>();
        for (int i = 0; i < operateCraftReq.getBatchCraftReq().size(); i++) {
            ProcessCraftEntity processCraftEntity = new ProcessCraftEntity();
            BeanUtil.copyProperties(operateCraftReq.getBatchCraftReq().get(i), processCraftEntity);
            // 重新生成自增序列
            processCraftEntity.setSeq(i + 1);
            if (ObjectUtil.isNull(operateCraftReq.getBatchCraftReq().get(i).getId())) {
                // 新增的重新生成
                processCraftEntity.setProcessCode(operateCraftReq.getProcessCode());
                processCraftEntity.setVersion(operateCraftReq.getVersion());
                processCraftEntity.setFigureNo(operateCraftReq.getFigureNo());
                processCraftEntity.setCode("craft" + "-" + UUIDUtil.getUUID());
            }
            updateProcessCraftList.add(processCraftEntity);
        }
        return updateProcessCraftList;
    }

    private void persistCraft(ProcessCraftDo processCraftDo) {
        // 删除工艺
        List<Integer> deleteIds = processCraftDo.getDeleteElement().stream().map(ProcessCraftEntity::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(deleteIds)) {
            processCraftProgramRepository.deleteBatch(new ArrayList<>(), deleteIds);
            processCraftMapper.deleteBatchIds(deleteIds);
        }
        // 新增工艺
        if (CollectionUtil.isNotEmpty(processCraftDo.getCreateElement())) {
            processCraftMapper.insertBatchSomeColumn(processCraftDo.getCreateElement());
        }
        // 修改工艺
        if (CollectionUtil.isNotEmpty(processCraftDo.getUpdateElement())) {
            processCraftMapper.updateBatchById(processCraftDo.getUpdateElement());
        }
    }

    private LambdaQueryWrapper<ProcessCraftEntity> buildProcessCraftWrapper(String processCode, Integer version) {
        LambdaQueryWrapper<ProcessCraftEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProcessCraftEntity::getProcessCode, processCode);
        wrapper.eq(ProcessCraftEntity::getVersion, version);
        return wrapper;
    }

    /**
     * 编辑删除新增物料
     *
     * @return
     */
//    public Boolean editOrAddBom(OperateBomReq operateBomReq) throws ToolManageException {
//        if (StringUtils.isEmpty(operateBomReq.getProcessCode())) {
//            throw new ToolManageException(ToolManageEx.PROCESS_BOM_CONNECT_ERROR.getCode(), ToolManageEx.PROCESS_BOM_CONNECT_ERROR.getMsg());
//        }
//        LambdaQueryWrapper<ProcessBomEntity> wrapper = buildBomWrapper(operateBomReq.getProcessCode(), operateBomReq.getVersion());
//        List<ProcessBomEntity> originProcessBomList = processBomMapper.selectList(wrapper);
//        List<ProcessBomEntity> updateProcessBomList = transferProcessBom(operateBomReq);
//
//        ProcessBomLogic processBomLogic = new ProcessBomLogic(originProcessBomList, updateProcessBomList);
//        processBomLogic.buildProcessBomDo();
//        ProcessBomDo processBomDo = processBomLogic.getProcessBomDo();
//        // 持久化
//        persistBom(processBomDo);
//        return Boolean.TRUE;
//    }
    private void persistBom(ProcessBomDo processBomDo) {
        // 删除物料
        List<Integer> deleteIds = processBomDo.getDeleteElement().stream().map(ProcessBomEntity::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(deleteIds)) {
            processBomMapper.deleteBatchIds(deleteIds);
        }
        // 新增物料
        if (CollectionUtil.isNotEmpty(processBomDo.getCreateElement())) {
            processBomMapper.insertBatchSomeColumn(processBomDo.getCreateElement());
        }
        // 修改物料
        if (CollectionUtil.isNotEmpty(processBomDo.getUpdateElement())) {
            processBomMapper.updateBatchById(processBomDo.getUpdateElement());
        }
    }

//    private List<ProcessBomEntity> transferProcessBom(OperateBomReq operateBomReq) {
//        if (CollectionUtil.isEmpty(operateBomReq.getBatchUpdateReq())) {
//            return Collections.emptyList();
//        }
//        List<ProcessBomEntity> updateProcessBomList = new ArrayList<>();
//        for (int i = 0; i < operateBomReq.getBatchUpdateReq().size(); i++) {
//            ProcessBomEntity processBomEntity = new ProcessBomEntity();
//            BeanUtil.copyProperties(operateBomReq.getBatchUpdateReq().get(i), processBomEntity);
//            // 重新生成自增序列
//            processBomEntity.setSeq(i + 1);
//            if (ObjectUtil.isNull(operateBomReq.getBatchUpdateReq().get(i).getId())) {
//                // 新增的重新生成
//                processBomEntity.setProcessCode(operateBomReq.getProcessCode());
//                processBomEntity.setVersion(operateBomReq.getVersion());
//                processBomEntity.setFigureNo(operateBomReq.getFigureNo());
//                processBomEntity.setCode("bom" + "-" + UUIDUtil.getUUID());
//            }
//            updateProcessBomList.add(processBomEntity);
//        }
//        return updateProcessBomList;
//    }

    private LambdaQueryWrapper<ProcessBomEntity> buildBomWrapper(String processCode, Integer version) {
        LambdaQueryWrapper<ProcessBomEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProcessBomEntity::getProcessCode, processCode);
        wrapper.eq(ProcessBomEntity::getVersion, version);
        return wrapper;
    }

    /**
     * 关联程序编码
     *
     * @param connectReq connectReq
     */
    public boolean connectProgram(ConnectReq connectReq) throws ToolManageException {
        ProcessCraftEntity processCraftEntity = processCraftMapper.selectById(connectReq.getCraftId());
        if (ObjectUtil.isNull(processCraftEntity)) {
            throw new ToolManageException(ToolManageEx.PROCESS_CRAFT_NO_EXIST.getCode(), ToolManageEx.PROCESS_CRAFT_NO_EXIST.getMsg());
        }
        // 关联主程序
        processCraftEntity.setProgramCode(connectReq.getProgramCode());
        processCraftEntity.setSingleTimeConsuming(new BigDecimal(subProgramRespository.queryHandleTime(connectReq.getProgramCode())));
        processCraftMapper.updateById(processCraftEntity);
        return Boolean.TRUE;
    }

    /**
     * 查询单个工序
     *
     * @param figureNo figureNo
     * @param version  version
     * @return
     */
    public String querySingleProcess(String figureNo, Integer version) throws ToolManageException {
        LambdaQueryWrapper<ProcessEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProcessEntity::getFigureNo, figureNo).eq(ProcessEntity::getVersion, version);
        ProcessEntity processEntity = processMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(processEntity)) {
            throw new ToolManageException(ToolManageEx.PROCESS_NO_EXIST.getCode(), ToolManageEx.PROCESS_NO_EXIST.getMsg());
        }
        return processEntity.getCode();
    }

    @Transactional
    public synchronized void taskAllocation(AllocationReq allocationReq) throws ToolManageException {
        QueryWrapper<OrderCraftEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", allocationReq.getTaskId());
        OrderCraftEntity orderCraftEntity = orderCraftMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(orderCraftEntity)) {
            throw new ToolManageException(ToolManageEx.ORDER_NO_EXIST.getCode(), ToolManageEx.ORDER_NO_EXIST.getMsg());
        }
        //任务校验
        if(CollectionUtil.isNotEmpty(allocationReq.getAllocationReqList())){
            for (SingleAllocationReq singleAllocationReq : allocationReq.getAllocationReqList()) {
                if(ObjectUtil.isNull(singleAllocationReq.getNumber())){
                    continue;
                }
                List<MachineToolTaskEntity> taskEntities = machineToolTaskRespository.getTaskListByEquipmentName(singleAllocationReq.getMachineToolId());
                if(CollectionUtil.isNotEmpty(taskEntities)){
                    for (MachineToolTaskEntity taskEntity : taskEntities) {
                        if((taskEntity.getStartTime().compareTo(singleAllocationReq.getStartTime()) > 0 && taskEntity.getStartTime().compareTo(singleAllocationReq.getEndTime()) <0) || (taskEntity.getEndTime().compareTo(singleAllocationReq.getStartTime()) > 0 && taskEntity.getEndTime().compareTo(singleAllocationReq.getEndTime()) <0)){
                            throw new ToolManageException(ToolManageEx.TIME_CONFLICT.getCode(), ToolManageEx.TIME_CONFLICT.getMsg());
                        }
                    }
                }
            }
        }
        //获取任务分配列表
        buildMachineToolTaskEntity(allocationReq, orderCraftEntity);
        //任务分配完修改工单任务分配状态
        LambdaQueryWrapper<OrderEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderEntity::getTaskId, allocationReq.getTaskId());
        OrderEntity orderEntity = orderMapper.selectOne(lambdaQueryWrapper);
        orderEntity.setOrderStatus(1);
        orderMapper.updateById(orderEntity);
    }


    private void buildMachineToolTaskEntity(AllocationReq allocationReq, OrderCraftEntity orderCraftEntity) throws ToolManageException {
        Integer unallocatedNumber = null;
        //设置可分配数量
        if (allocationReq.getCraftUnallocatedNumber() == 0) {
            unallocatedNumber = allocationReq.getPlanNumber();
        } else {
            unallocatedNumber = allocationReq.getCraftUnallocatedNumber();
        }
        //校验可分配数量与分配数量大小
        int allocatedNumber = allocationReq.getAllocationReqList()
                .stream()
                .filter(singleAllocationReq -> ObjectUtil.isNotNull(singleAllocationReq.getNumber()))
                .mapToInt(SingleAllocationReq::getNumber).sum();
        if (allocatedNumber > unallocatedNumber) {
            throw new ToolManageException(ToolManageEx.EXCEED_PLAN_NUMBER.getCode(), ToolManageEx.EXCEED_PLAN_NUMBER.getMsg());
        }
        //分配任务到对应机床
        allocationReq.getAllocationReqList()
                .stream()
                .filter(singleAllocationReq -> ObjectUtil.isNotNull(singleAllocationReq.getNumber()))
                .forEach(singleAllocationReq -> {
                    MachineToolTaskEntity machineToolTaskEntity = new MachineToolTaskEntity();
                    BeanUtils.copyProperties(singleAllocationReq, machineToolTaskEntity);
                    WarehouseEntity warehouseEntity = warehouseRespository.selectOperatorById(machineToolTaskEntity.getMachineToolId());
                    machineToolTaskEntity.setOperator(warehouseEntity.getOperator());//设置任务分配机床的负责人
                    machineToolTaskEntity.setOrderSnapshotCraftSeq(allocationReq.getSeq());//设置关联字段
                    machineToolTaskEntity.setOrderTaskId(orderCraftEntity.getTaskId());//设置关联字段
                    machineToolTaskEntity.setCraftName(allocationReq.getName());
                    machineToolTaskEntity.setContent(allocationReq.getContent());
                    machineToolTaskEntity.setMachineToolName(warehouseRespository.getNameByWarehouseId(warehouseEntity.getId()));
                    machineToolTaskEntity.setIsDone(CommonConstant.NOT_DONE_CONST);
                    //分配数量*单个工序时长 = 任务所用时长
                    machineToolTaskEntity.setHandleTime(new BigDecimal(singleAllocationReq.getNumber())
                            .multiply(new BigDecimal(ObjectUtil.isNull(allocationReq.getSingleTimeConsuming()) ? "0" : allocationReq.getSingleTimeConsuming())));
                    machineToolTaskEntity.setCreateTime(new Date());
                    machineToolTaskEntity.setIsDone(0);
                    machineToolTaskMapper.insert(machineToolTaskEntity);
                });
        //设置可分配任务数量
        setCraftAllocationNumber(unallocatedNumber, orderCraftEntity, allocatedNumber, allocationReq.getCode() , allocationReq.getTypeFlag());
    }

    private void setCraftAllocationNumber(Integer unallocatedNumber, OrderCraftEntity orderCraftEntity, Integer allocatedNumber, String code , Integer typeFlag) {
        //匹配对应的工序
        List<CraftParamVo> craftParamVoList = JSONArray.parseArray(orderCraftEntity.getCraftParam(), CraftParamVo.class).stream().
                sorted(Comparator.comparingInt(CraftParamVo::getSeq)).
                collect(Collectors.toList());
        craftParamVoList.forEach(craftParamVo -> {
            if (craftParamVo.getCode().equals(code)) {
                //计划数量为空，设置计划数量
                if (craftParamVo.getCraftPlanNumber() == 0) {
                    craftParamVo.setCraftPlanNumber(unallocatedNumber);
                }
                craftParamVo.setTypeFlag(typeFlag);
                //设置未分配数量
                craftParamVo.setCraftUnallocatedNumber(unallocatedNumber - allocatedNumber);
                orderCraftEntity.setCraftParam(JSONArray.toJSONString(craftParamVoList));
                orderCraftMapper.updateById(orderCraftEntity);
            }
        });
    }

    @Transactional
    public Object editCraftTask(EditCraftTaskReq editCraftTaskReq) throws ToolManageException {
        QueryWrapper<EmployeeMachineToolConnectEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("machine_tool_task_id", editCraftTaskReq.getId());
        employeeMachineToolConnectMapper.delete(wrapper);
        machineToolTaskMapper.deleteById(editCraftTaskReq.getId());
        taskAllocation(editCraftTaskReq.getAllocationReq());
        return Boolean.TRUE;
    }


    public PageResult<MachineToolVo> qryMachineToolList(QryMachineToolReq machineToolReq) {
        List<MachineToolVo> pageList = new ArrayList<>();
        List<MachineToolVo> warehouseEntities = warehouseRespository.selectMachineToolList(machineToolReq);
        if (CollectionUtil.isNotEmpty(warehouseEntities) && StringUtil.isNotEmpty(machineToolReq.getGroupType())) {
            List<Integer> ids = equipmentGroupRepository.selectByGroupType(machineToolReq.getGroupType());
            warehouseEntities = warehouseEntities.stream().filter(machineToolVo -> ids.contains(machineToolVo.getId())).collect(Collectors.toList());
        }
        //手动分页
        if (CollectionUtil.isNotEmpty(warehouseEntities)) {
            pageList = CommonUtil.pageList(warehouseEntities, machineToolReq.getPageNum(), machineToolReq.getPageSize());
        }
        return new PageResult<>(pageList, (long) warehouseEntities.size());
    }

    public Object queryEquipmentTaskList(QueryEquipmentTaskListReq queryEquipmentTaskListReq) {
        Map<String, Object> retMap = new HashMap<>();
        List<EquipmentTaskBuildVo> equipmentTaskBuildVos = machineToolTaskRespository.selectEquipmentTaskList(queryEquipmentTaskListReq);
        List<EquipmentTaskVo> equipmentTaskVos = equipmentTaskBuildVos
                .stream().map(this::getEquipmentTaskList).collect(Collectors.toList());
        //状态过滤
        if (ObjectUtil.isNotNull(queryEquipmentTaskListReq.getStatus()) && CollectionUtil.isNotEmpty(equipmentTaskVos)) {
            equipmentTaskVos = equipmentTaskVos.stream().filter(equipmentTaskVo -> equipmentTaskVo.getStatus().equals(queryEquipmentTaskListReq.getStatus())).collect(Collectors.toList());
        }
        //根据车间名称分组
        Map<String, List<EquipmentTaskVo>> groupByMachineToolNameMap = equipmentTaskVos
                .stream().collect(Collectors.groupingBy(EquipmentTaskVo::getMachineToolName));
        //构建机床名列表
        List<String> machineToolNameList = warehouseRespository.getMachineToolNameList(WarehouseConstant.MACHINE_TOOL_CABINET);
        if (CollectionUtil.isNotEmpty(queryEquipmentTaskListReq.getMachineNames())) {
            machineToolNameList = machineToolNameList.stream().filter(s -> queryEquipmentTaskListReq.getMachineNames().contains(s)).collect(Collectors.toList());
        }
        List<EquipmentTaskResultVo> equipmentTaskResultVoList = machineToolNameList.stream().map(this::buildEquipmentTaskResultVo).collect(Collectors.toList());
        //构建返回结构
        if (CollectionUtil.isNotEmpty(groupByMachineToolNameMap)) {
            //机床有任务分配
            Set<Map.Entry<String, List<EquipmentTaskVo>>> entries = groupByMachineToolNameMap.entrySet();
            for (Map.Entry<String, List<EquipmentTaskVo>> entry : entries) {
                for (EquipmentTaskResultVo equipmentTaskResultVo : equipmentTaskResultVoList) {
                    if (equipmentTaskResultVo.getName().equals(entry.getKey())) {
                        List<EquipmentTaskVo> taskList = entry.getValue();
                        //根据任务名称来筛选
                        if (StringUtil.isNotEmpty(queryEquipmentTaskListReq.getType()) && CollectionUtil.isNotEmpty(entry.getValue())) {
                            taskList = entry.getValue()
                                    .stream()
                                    .filter(equipmentTaskVo -> equipmentTaskVo.getName().contains(queryEquipmentTaskListReq.getType()))
                                    .collect(Collectors.toList());
                        }
//                        if (CollectionUtil.isNotEmpty(taskList)) {
//                            taskList.forEach(equipmentTaskVo -> {
//                                List<MachineToolProgramEntity> machineToolProgramEntities = processRepository.selectProgramByPartno(equipmentTaskVo.getTaskId());
//                            });
//                        }
                        equipmentTaskResultVo.setEquipmentTaskVoList(taskList);
                    }
                }
            }
            retMap.put("resultList", equipmentTaskResultVoList
                    .stream()
                    //.filter(equipmentTaskResultVo -> CollectionUtil.isNotEmpty(equipmentTaskResultVo.getEquipmentTaskVoList()))
                    .sorted(Comparator.comparingInt(equipmentTaskResultVo -> Integer.parseInt(equipmentTaskResultVo.getName().substring(1))))
                    .collect(Collectors.toList()));
        } else {
            equipmentTaskResultVoList.forEach(equipmentTaskResultVo -> equipmentTaskResultVo.setEquipmentTaskVoList(new ArrayList<>()));
            equipmentTaskResultVoList = equipmentTaskResultVoList
                    .stream()
                    .sorted(Comparator.comparingInt(equipmentTaskResultVo -> Integer.parseInt(equipmentTaskResultVo.getName().substring(1))))
                    .collect(Collectors.toList());
            //机床无任务分配
            retMap.put("resultList", equipmentTaskResultVoList);
        }
        //计算总耗时
        buildTotalTime(retMap, groupByMachineToolNameMap);
        return retMap;
    }

    private EquipmentTaskResultVo buildEquipmentTaskResultVo(String s) {
        EquipmentTaskResultVo equipmentTaskResultVo = new EquipmentTaskResultVo();
        equipmentTaskResultVo.setName(s);
        return equipmentTaskResultVo;
    }

    private static void buildTotalTime(Map<String, Object> retMap, Map<String, List<EquipmentTaskVo>> groupByMachineToolNameMap) {
        double totalTime = 0.00;
        for (Map.Entry<String, List<EquipmentTaskVo>> stringListEntry : groupByMachineToolNameMap.entrySet()) {
            //计算每台机床任务耗时并累加
            double singleEquipmentTaskTime = stringListEntry.getValue()
                    .stream()
                    .filter(equipmentTaskVo -> ObjectUtil.isNotNull(equipmentTaskVo.getHandleTime()))//没有任务的跳过
                    .mapToDouble(value -> value.getHandleTime().doubleValue()).sum();//计算单个机床总用时
            totalTime += singleEquipmentTaskTime;
        }
        retMap.put("totalTime", totalTime);
    }

    private EquipmentTaskVo getEquipmentTaskList(EquipmentTaskBuildVo equipmentTaskBuildVo) {
        EquipmentTaskVo equipmentTaskVo = new EquipmentTaskVo();
        BeanUtils.copyProperties(equipmentTaskBuildVo, equipmentTaskVo);
        List<CraftParamVo> craftParamVos = JSONArray.parseArray(equipmentTaskBuildVo.getCraftParam(), CraftParamVo.class);
        if (CollectionUtil.isNotEmpty(craftParamVos)) {
            craftParamVos.forEach(craftParamVo -> {
                if (Objects.equals(craftParamVo.getSeq(), equipmentTaskBuildVo.getSeq())) {
                    equipmentTaskVo.setCode(craftParamVo.getCode());
                    equipmentTaskVo.setName(craftParamVo.getName());
                    equipmentTaskVo.setProgramCode(craftParamVo.getProgramCode());
                    equipmentTaskVo.setContent(craftParamVo.getContent());
                }
            });
        }
        //设置任务程序满足状态（0：未满足   1：满足）
        equipmentTaskVo.setStatus(queryProgramStatus(equipmentTaskBuildVo.getMaterialNo(), equipmentTaskVo.getContent(), equipmentTaskVo.getMachineToolId())? 1:0);
        return equipmentTaskVo;
    }

    public Boolean queryProgramStatus(String materialNo, String craftContent , Integer machineToolId) {
        QueryWrapper<MachineToolProgramEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("partno", materialNo);
        List<MachineToolProgramEntity> machineToolProgramList = machineToolProgramMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(machineToolProgramList)) {
            machineToolProgramList = machineToolProgramList
                    .stream()
                    .filter(machineToolProgramEntity ->
                            StringUtils.isNotEmpty(machineToolProgramEntity.getMachineToolIds()) && !machineToolProgramEntity.getMachineToolIds().equals("[]")
                    ).distinct().collect(Collectors.toList());
            //校验工序内容描述是否有粗铣 或精铣
            if (CollectionUtil.isNotEmpty(machineToolProgramList) && craftContent.contains("粗铣")) {
                machineToolProgramList = machineToolProgramList.stream().filter(machineToolProgramEntity -> machineToolProgramEntity.getProgram().toLowerCase().contains("cxdc")).collect(Collectors.toList());
            } else if (CollectionUtil.isNotEmpty(machineToolProgramList) && craftContent.contains("精铣")) {
                machineToolProgramList = machineToolProgramList.stream().filter(machineToolProgramEntity -> machineToolProgramEntity.getProgram().toLowerCase().contains("jxdc")).collect(Collectors.toList());
            }
            List<Integer> machineToolIdList = new ArrayList<>();

            machineToolProgramList.forEach(machineToolProgramEntity -> {
                machineToolIdList.addAll(JSONArray.parseArray(machineToolProgramEntity.getMachineToolIds(), Integer.class));
            });
            if (CollectionUtil.isEmpty(machineToolIdList)) {
                //无对应机床
                //equipmentTaskVo.setStatus(0);
                return Boolean.FALSE;
            } else {
                //有机床列表
                //equipmentTaskVo.setStatus(machineToolIdList.contains(equipmentTaskVo.getMachineToolId()) ? 1 : 0);
                return machineToolIdList.contains(machineToolId) ? Boolean.TRUE : Boolean.FALSE;
            }
        }
        //equipmentTaskVo.setStatus(0);
        return Boolean.FALSE;

    }

    @Transactional
    public void setProcessStatus(SetProcessStatusReq setProcessStatusReq) throws ToolManageException {
        //设置工艺状态
        QueryWrapper<ProcessEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id", setProcessStatusReq.getId());
        ProcessEntity processEntity = processMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(processEntity)) {
            throw new ToolManageException(ToolManageEx.PROCESS_NO_EXIST.getCode(), ToolManageEx.PROCESS_NO_EXIST.getMsg());
        }
        //校验工艺是否关联了程序
//        List<Integer> existRecord = processRepository.qryConnectProgram(processEntity.getCode());
//        if(CollectionUtil.isEmpty(existRecord)){
//            throw new ToolManageException(ToolManageEx.PROCESS_CRAFT_NOT_CONNECT_PROGRAM.getCode() , ToolManageEx.PROCESS_CRAFT_NOT_CONNECT_PROGRAM.getMsg());
//        }
        processEntity.setStatus(setProcessStatusReq.getStatus());
        processMapper.updateById(processEntity);
        //设置工艺关联的产品的状态字段
        List<String> materialNoList = processRepository.selectFigureNoByCode(processEntity.getCode());
        if (CollectionUtil.isNotEmpty(materialNoList)) {
            materialNoList.forEach(s -> {
                ProductionEntity productionEntity = productionManageService.getProductionEntity(s);
                if (ObjectUtil.isNotNull(productionEntity)) {
                    productionEntity.setProcessStatus(setProcessStatusReq.getStatus());
                    productionManageService.setProductionStatus(productionEntity);
                }
            });
        }

    }

    public Object qryMachineToolChildrenList(MachineToolChildReq machineToolChildReq) {
        if (ObjectUtil.isNull(machineToolChildReq.getStartTime())) {
            machineToolChildReq.setStartTime(new Date());
            machineToolChildReq.setEndTime(CommonUtil.addTime48h());
        }
        List<EquipmentTaskBuildVo> equipmentTaskBuildVos = machineToolTaskRespository.selectTask(machineToolChildReq);
        return equipmentTaskBuildVos
                .stream()
                .map(this::getEquipmentTaskList)
                .collect(Collectors.toList());
    }

    public Map<String, String> queryCodeByFigureNo(String materialNo) throws ToolManageException {
        String code = processRepository.selectCodeByFigureNo(materialNo);
        Map<String, String> retMap = new HashMap<>();
        String resultCode = StringUtils.isNotEmpty(code) ? code : "";
        retMap.put("code", resultCode);
        return retMap;
    }

    public Object getMachineToolOrderDetail(String taskId) throws ToolManageException {
        Map<String, Object> retMap = new HashMap<>();
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", taskId);
        OrderEntity orderEntity = orderMapper.selectOne(wrapper);
        retMap.put("productionName", orderEntity.getProductionName());
        retMap.put("productionNum", orderEntity.getProductionNum());
        return retMap;
    }


    @Transactional
    public Object pucAndProConnectReq(PucAndProConnectReq pucAndProConnectReq) {
        //获取对应产品以及工艺对象
        QueryWrapper<ProductionEntity> productionWrapper = new QueryWrapper<>();
        productionWrapper.eq("material_no", pucAndProConnectReq.getMaterialNo());
        ProductionEntity productionEntity = productionMapper.selectOne(productionWrapper);
        QueryWrapper<ProcessEntity> processWrapper = new QueryWrapper<>();
        processWrapper.eq("code", pucAndProConnectReq.getProcessCode());
        ProcessEntity processEntity = processMapper.selectOne(processWrapper);
        //设置使用状态为0
        setUsingStatus(productionEntity.getId());
        //新建关联关系
        ProductionProcessEntity productionProcessEntity = new ProductionProcessEntity();
        productionProcessEntity.setProcessId(processEntity.getId());
        productionProcessEntity.setProductionId(productionEntity.getId());
        productionProcessEntity.setIsUsing(1);
        productionProcessMapper.insert(productionProcessEntity);
        //设置对应产品的关联状态以及总状态
        productionEntity.setProductionProcessConnectStatus(CommonConstant.PRODUCTION_PROCESS_CONNECT);
        productionEntity.setProcessStatus(processEntity.getStatus());
        productionManageService.setProductionStatus(productionEntity);
        return Boolean.TRUE;
    }

    private void setUsingStatus(Integer id) {
        QueryWrapper<ProductionProcessEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("production_id", id);
        List<ProductionProcessEntity> selectList = productionProcessMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(selectList)) {
            List<ProductionProcessEntity> updateList = selectList
                    .stream()
                    .peek(productionProcessEntity -> productionProcessEntity.setIsUsing(0))
                    .collect(Collectors.toList());
            productionProcessMapper.updateBatchById(updateList);
        }
    }

    @Transactional
    public Object abutmentProcess(String processNum) {

//        String get = HttpUtil.get(UrlConstant.PROCESS_MANAGEMENT_SYNC_URL + "/abutmentProcess?processNum=" + processNum);
        List<AbutmentProcessCraftEntity> abutmentProcessCrafts = querySqlServerService.abutmentProcess(processNum);
        if (CollectionUtil.isNotEmpty(abutmentProcessCrafts)) {
            //新增工序集合
            List<ProcessCraftEntity> addProcessCraftEntities = new ArrayList<>();
            //删除工序集合
            List<ProcessCraftEntity> deleteProductionEntities = new ArrayList<>();
            QueryWrapper<ProcessEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("process_num", processNum);
            ProcessEntity processEntity = processMapper.selectOne(wrapper);
            String processCode = processEntity.getCode();
            QueryWrapper<ProcessCraftEntity> craftWrapper = new QueryWrapper<>();
            craftWrapper.eq("process_code", processCode);
            List<ProcessCraftEntity> processCraftEntities = processCraftMapper.selectList(craftWrapper);
            //过滤掉关联程序字段为空的
            deleteProductionEntities = processCraftEntities.stream().filter(processCraftEntity -> StringUtil.isEmpty(processCraftEntity.getProgramCode())).collect(Collectors.toList());
            processCraftEntities = processCraftEntities.stream().filter(processCraftEntity -> StringUtil.isNotEmpty(processCraftEntity.getProgramCode())).collect(Collectors.toList());

//            List<AbutmentProcessCraft> abutmentProcessCrafts = JSONArray.parseArray(get, AbutmentProcessCraft.class);
            if (CollectionUtil.isNotEmpty(abutmentProcessCrafts)) {
                //List<ProcessEntity> addProcessEntities = new ArrayList<>();
                //获取关联了程序的工序序号列表
//                List<Integer> seqList = new ArrayList<>();
//                for (ProcessCraftEntity processCraftEntity : processCraftEntities) {
//                    Integer seq = processCraftEntity.getSeq();
//                    if (ObjectUtil.isNotNull(seq)) {
//                        seqList.add(seq);
//                    }
//                }
//                abutmentProcessCrafts = abutmentProcessCrafts.stream().filter(abutmentProcessCraft -> seqList.contains(abutmentProcessCraft.getSeq())).collect(Collectors.toList());
                //过滤后不为空
                if (CollectionUtil.isNotEmpty(abutmentProcessCrafts)) {
                    abutmentProcessCrafts.forEach(abutmentProcessCraft -> {
                        ProcessCraftEntity processCraftEntity = new ProcessCraftEntity();
                        BeanUtil.copyProperties(abutmentProcessCraft, processCraftEntity);
                        processCraftEntity.setProcessCode(processCode);
                        processCraftEntity.setCode("craft-" + UUIDUtil.getUUID());
                        processCraftEntity.setSingleTimeConsuming(BigDecimal.valueOf(abutmentProcessCraft.getSingleTime()));
                        addProcessCraftEntities.add(processCraftEntity);
                    });
                }
            }
            //批量删除工序
            if (CollectionUtil.isNotEmpty(deleteProductionEntities)) {
                processCraftMapper.deleteBatchIds(deleteProductionEntities.stream().map(ProcessCraftEntity::getId).collect(Collectors.toList()));
            }
            //批量修改产品
            if (CollectionUtil.isNotEmpty(addProcessCraftEntities)) {
                processCraftMapper.insertBatchSomeColumn(addProcessCraftEntities);
            }
        }
        return Boolean.TRUE;
    }

    public void importAllotEmployee(List<AllotEmployeeImport> importData , String date) throws IllegalAccessException, ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String present = sdf.format(new Date());
        QueryWrapper<AllotEmployeeEntity> wrapper = new QueryWrapper<>();
        if(StringUtil.isNotEmpty(date)){
            wrapper.le("start_time", date);
        }else {
            wrapper.le("start_time", present);
        }
        allotEmployeeMapper.delete(wrapper);
        List<String> everyDay = new ArrayList<>();
        List<AllotEmployeeEntity> insertList = new ArrayList<>();
        if(StringUtil.isNotEmpty(date)){
            everyDay = CommonUtil.findEveryDayReload(date, sdf.format(getDate(sdf.parse(date))));
        }else{
            everyDay = CommonUtil.findEveryDayReload(present, sdf.format(getDate(new Date())));
        }
        for (AllotEmployeeImport importDatum : importData) {
            String equipmentName = importDatum.getEquipmentName();
            String[] nameSplit = equipmentName.split("-");
            Field[] declaredFields = importDatum.getClass().getDeclaredFields();
            //循环单条数据
            for (int i = 1; i < declaredFields.length; i++) {
                declaredFields[i].setAccessible(true);
                AllotEmployeeEntity allotEmployeeEntity = new AllotEmployeeEntity();
                //获取设置机床名
                allotEmployeeEntity.setEquipmentName(nameSplit[1]);
                allotEmployeeEntity.setEmployeeName(declaredFields[i].get(importDatum).toString());
                //设置开始时间和结束时间
                //判断奇偶
                if ((i & 1) == 1) {
                    allotEmployeeEntity.setStartTime(getDateByDateString(everyDay.get(i), 8, 0, 0));
                    allotEmployeeEntity.setEndTime(getDateByDateString(everyDay.get(i), 16, 0, 0));
                } else {
                    allotEmployeeEntity.setStartTime(getDateByDateString(everyDay.get(i), 16, 0, 0));
                    allotEmployeeEntity.setEndTime(getDateByDateString(everyDay.get(i), 24, 0, 0));
                }
                insertList.add(allotEmployeeEntity);
            }
        }
        if (CollectionUtil.isNotEmpty(insertList)) {
            allotEmployeeMapper.insertBatchSomeColumn(insertList);
        }
    }

    private Date getDate(Date date) {
        //Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH, 15);
        return cal.getTime();
    }

    private Date getDateByDateString(String dateString, Integer hour, Integer minute, Integer second) {
        Calendar cal = Calendar.getInstance();
        String[] split = dateString.split("-");
        cal.set(Calendar.YEAR, Integer.parseInt(split[0]));
        cal.set(Calendar.MONTH, Integer.parseInt(split[1]) - 1);
        cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(split[2]));
        cal.set(Calendar.HOUR_OF_DAY, hour);
        cal.set(Calendar.MINUTE, minute);
        cal.set(Calendar.SECOND, second);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    public String qryAllotEmployee(QryAllotEmployeeReq qryAllotEmployeeReq) {
        QueryWrapper<AllotEmployeeEntity> wrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(qryAllotEmployeeReq.getEquipmentName())) {
            wrapper.eq("equipment_name", qryAllotEmployeeReq.getEquipmentName());
        }
        if (ObjectUtil.isNotNull(qryAllotEmployeeReq.getStartTime())) {
            wrapper.le("start_Time", qryAllotEmployeeReq.getStartTime()).ge("end_time", qryAllotEmployeeReq.getEndTime());
        }
        AllotEmployeeEntity allotEmployeeEntity = allotEmployeeMapper.selectOne(wrapper);
        if (ObjectUtil.isNotNull(allotEmployeeEntity)) {
            return allotEmployeeEntity.getEmployeeName();
        }
        return "";
    }

    public Object checkAllotEmployee(CheckAllotEmployeeReq checkAllotEmployeeReq) {
        PageHelper.startPage(checkAllotEmployeeReq.getPageNum(), checkAllotEmployeeReq.getPageSize());
        PageInfo<AllotEmployeeEntity> pageInfo = new PageInfo<>(allotEmployeeRepository.selectByCondition(checkAllotEmployeeReq));
        return new PageResult<>(pageInfo.getList(), (long) pageInfo.getTotal());
    }

    public Object addOrEditAllotEmployee(AllotEmployeeEntity allotEmployeeEntity) {
        if (ObjectUtil.isNotNull(allotEmployeeEntity.getId())) {
            //修改
            allotEmployeeMapper.updateById(allotEmployeeEntity);
        } else {
            //新增
            allotEmployeeMapper.insert(allotEmployeeEntity);
        }
        return Boolean.TRUE;
    }

    public Object deleteAllotEmployee(Integer id) {
        if (ObjectUtil.isNotNull(id)) {
            allotEmployeeMapper.deleteById(id);
        }
        return Boolean.TRUE;
    }

    public Object checkAllotEmployeeGroup(CheckAllotEmployeeGroupReq checkAllotEmployeeGroupReq) {
        return allotEmployeeRepository.checkAllotEmployeeGroup(checkAllotEmployeeGroupReq.getStartTime(), checkAllotEmployeeGroupReq.getEndTime());
    }

    public List<String> checkAllotEmployeeGroup(Date startTime, Date endTime) {
        return allotEmployeeRepository.checkAllotEmployeeGroup(startTime, endTime);
    }

    public Object allotEmployeeChart(AllotEmployeeChartReq allotEmployeeChartReq) {
        Map<String, Object> retMap = new HashMap<>();
        //根据人名过滤
        QueryWrapper<AllotEmployeeEntity> wrapper = new QueryWrapper<>();
        if (CollectionUtil.isNotEmpty(allotEmployeeChartReq.getEmployeeNames())) {
            wrapper.in("employee_name", allotEmployeeChartReq.getEmployeeNames());
        }
        List<AllotEmployeeEntity> allotEmployeeEntities = allotEmployeeMapper.selectList(wrapper);
        //根据车间名称分组
        Map<String, List<AllotEmployeeEntity>> groupByMachineToolNameMap = allotEmployeeEntities
                .stream().collect(Collectors.groupingBy(AllotEmployeeEntity::getEquipmentName));
        //构建机床名列表
        List<String> machineToolNameList = warehouseRespository.getMachineToolNameList(WarehouseConstant.MACHINE_TOOL_CABINET);
        if (CollectionUtil.isNotEmpty(allotEmployeeChartReq.getEquipmentNames())) {
            machineToolNameList = machineToolNameList.stream().filter(s -> allotEmployeeChartReq.getEquipmentNames().contains(s)).collect(Collectors.toList());
        }
        List<AllotEmployeeVo> allotEmployeeVos = machineToolNameList.stream().map(this::buildAllotEmployeeVo).collect(Collectors.toList());
        //构建返回结构
        if (CollectionUtil.isNotEmpty(groupByMachineToolNameMap)) {
            //机床有人员分配
            Set<Map.Entry<String, List<AllotEmployeeEntity>>> entries = groupByMachineToolNameMap.entrySet();
            for (Map.Entry<String, List<AllotEmployeeEntity>> entry : entries) {
                for (AllotEmployeeVo allotEmployeeVo : allotEmployeeVos) {
                    if (allotEmployeeVo.getName().equals(entry.getKey())) {
                        allotEmployeeVo.setAllotList(entry.getValue());
                    }
                }
            }
            retMap.put("resultList", allotEmployeeVos
                    .stream()
                    //.filter(equipmentTaskResultVo -> CollectionUtil.isNotEmpty(equipmentTaskResultVo.getEquipmentTaskVoList()))
                    .sorted(Comparator.comparingInt(allotEmployeeVo -> Integer.parseInt(allotEmployeeVo.getName().substring(1))))
                    .collect(Collectors.toList()));
        } else {
            allotEmployeeVos.forEach(allotEmployeeVo -> allotEmployeeVo.setAllotList(new ArrayList<>()));
            allotEmployeeVos = allotEmployeeVos.stream().sorted(Comparator.comparingInt(allotEmployeeVo -> Integer.parseInt(allotEmployeeVo.getName().substring(1)))).collect(Collectors.toList());
            //机床无人员分配详情
            retMap.put("resultList", allotEmployeeVos);
        }
        return retMap;
    }

    private AllotEmployeeVo buildAllotEmployeeVo(String s) {
        AllotEmployeeVo allotEmployeeVo = new AllotEmployeeVo();
        allotEmployeeVo.setName(s);
        return allotEmployeeVo;
    }

    public Object qryProcessCode(String processNum, Integer seq) {
        String trim = processNum.trim();
        return ObjectUtil.isNotNull(processRepository.qryProcessCode(trim, seq)) ? processRepository.qryProcessCode(trim, seq) : "";
    }

    public Object qryProgramCode(String programNum) {
        String trim = programNum.trim();
        return ObjectUtil.isNotNull(subProgramRespository.selectProgramCodeByProgramNum(trim)) ? subProgramRespository.selectProgramCodeByProgramNum(trim) : "";
    }

    public Object queryMachineToolTaskDetail(Integer id) {
        List<MachineToolTaskEntity> machineToolTaskEntities = new ArrayList<>();
        machineToolTaskEntities.add(machineToolTaskMapper.selectById(id));
        return machineToolTaskEntities;
    }

    public Object queryMachineToolTasks(QueryMachineToolTasksReq queryMachineToolTasksReq) {
        PageHelper.startPage(queryMachineToolTasksReq);
        QueryWrapper<MachineToolTaskEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("order_task_id", queryMachineToolTasksReq.getTaskId());
        if (ObjectUtil.isNotNull(queryMachineToolTasksReq.getStartTime())) {
            wrapper.ge("start_time", queryMachineToolTasksReq.getStartTime()).le("start_time", queryMachineToolTasksReq.getEndTime());
        }
        PageInfo<MachineToolTaskEntity> pageInfo = new PageInfo<>(machineToolTaskMapper.selectList(wrapper));
        return new PageResult<>(pageInfo.getList(), pageInfo.getTotal());
    }

    public Object qryMachineToolStatusHistory(HistoryStatusReq historyStatusReq) {
        List<StatusVo> resultList = machineToolStatusHistoryRepository.selectByCondition(historyStatusReq);
        List<StatusVo> pageList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(resultList)) {
            for (int i = 1; i < resultList.size(); i++) {
                if (ObjectUtil.isNotNull(resultList.get(i - 1).getCreateTime())
                        && ObjectUtil.isNotNull(resultList.get(i).getCreateTime()))
                    resultList.get(i - 1).setTimeStamp(resultList.get(i).getCreateTime().getTime() - resultList.get(i - 1).getCreateTime().getTime());
            }
        }
        if(StringUtils.isNotEmpty(historyStatusReq.getStatus())){
            resultList = resultList.stream().filter(statusVo -> statusVo.getStatus().equals(historyStatusReq.getStatus())).collect(Collectors.toList());
        }
        if(CollectionUtil.isNotEmpty(resultList)){
            pageList = CommonUtil.pageList(resultList , historyStatusReq.getPageNum() , historyStatusReq.getPageSize());
        }
        return new PageResult<>(pageList, (long)resultList.size());
    }

    public Object operateActualTime(Integer id, Integer type) {
        MachineToolTaskEntity machineToolTaskEntity = machineToolTaskMapper.selectById(id);
        if (ObjectUtil.isNotNull(machineToolTaskEntity)) {
            if (type == 0) {
                machineToolTaskEntity.setActualStartTime(new Date());
                //实际开始时间
                machineToolTaskMapper.updateById(machineToolTaskEntity);
                return type;
            }
            machineToolTaskEntity.setActualEndTime(new Date());
            //实际结束时间
            machineToolTaskMapper.updateById(machineToolTaskEntity);
            return type;
        }
        return type;
    }

    public Object editActualTime(EditActualTimeReq editActualTimeReq) {
        machineToolTaskRespository.editActualTime(editActualTimeReq);
        return Boolean.TRUE;
    }

    public Object editMachineToolStatusBz(Integer id, String bz) {
        machineToolStatusHistoryRepository.updateBzById(id, bz);
        return Boolean.TRUE;
    }

    public Object queryEquipmentTaskListReload(QueryEquipmentTaskLReqReload queryEquipmentTaskLReqReload) {
        List<EquipmentTaskBuildVo> equipmentTaskBuildVos = machineToolTaskRespository.selectEquipmentTaskList(queryEquipmentTaskLReqReload);
        List<EquipmentTaskVo> equipmentTaskVos = equipmentTaskBuildVos
                .stream().map(this::getEquipmentTaskList).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(equipmentTaskVos)){
            return new ArrayList<>();
        }
        //状态过滤
        if (ObjectUtil.isNotNull(queryEquipmentTaskLReqReload.getStatus()) && CollectionUtil.isNotEmpty(equipmentTaskVos)) {
            equipmentTaskVos = equipmentTaskVos.stream().filter(equipmentTaskVo -> equipmentTaskVo.getStatus().equals(queryEquipmentTaskLReqReload.getStatus())).collect(Collectors.toList());
        }
        //按已完成未完成过滤
        if(ObjectUtil.isNotNull(queryEquipmentTaskLReqReload.getIsDone()) && CollectionUtil.isNotEmpty(equipmentTaskVos)){
            equipmentTaskVos = equipmentTaskVos.stream().filter(equipmentTaskVo -> equipmentTaskVo.getIsDone().equals(queryEquipmentTaskLReqReload.getIsDone())).collect(Collectors.toList());
        }
        //按未确认已确认状态过滤过滤
        if(ObjectUtil.isNotNull(queryEquipmentTaskLReqReload.getConfirmFlag()) && CollectionUtil.isNotEmpty(equipmentTaskVos)){
            if(queryEquipmentTaskLReqReload.getConfirmFlag() == 1){
                equipmentTaskVos = equipmentTaskVos.stream().filter(equipmentTaskVo -> ObjectUtil.isNotNull(equipmentTaskVo.getConfirmFlag()) && equipmentTaskVo.getConfirmFlag().equals(queryEquipmentTaskLReqReload.getConfirmFlag())).collect(Collectors.toList());
            }else if(queryEquipmentTaskLReqReload.getConfirmFlag() == 0){
                equipmentTaskVos = equipmentTaskVos.stream().filter(equipmentTaskVo -> ObjectUtil.isNull(equipmentTaskVo.getConfirmFlag()) || ObjectUtil.isNotNull(equipmentTaskVo.getConfirmFlag())&&equipmentTaskVo.getConfirmFlag().equals(queryEquipmentTaskLReqReload.getConfirmFlag())).collect(Collectors.toList());
            }
        }
        //按开始时间排序
        if(StringUtils.isNotBlank(queryEquipmentTaskLReqReload.getSortCondition().getSortColumn())){
            //有排序字段按排序字段排序
            SortTaskEnum sortTaskEnum = SortTaskEnum.valueOf(sortEnumMap.getOrDefault(queryEquipmentTaskLReqReload.getSortCondition().getSortColumn() , ""));
            equipmentTaskVos = sortTaskEnum.sortByCondition(equipmentTaskVos , queryEquipmentTaskLReqReload.getSortCondition().getSortType());
        }else {
            //无排序字段按任务分配时间排序
            equipmentTaskVos =  equipmentTaskVos
                    .stream()
                    .sorted(Comparator.comparing(EquipmentTaskVo::getCreateTime))
                    .collect(Collectors.toList());
        }
        return equipmentTaskVos;
    }

    public void exportProcessTemplate(HttpServletResponse response) {
        String outputFileName = "工艺导入模版";
        CommonUtil.exportExcelFile(new Object() , "/template/process/工艺导入模版.xlsx" , response , outputFileName);
    }

    @Transactional
    public void importProcessTemplate(List<List<LinkedHashMap>> dataList) {
         List<ProcessEntity> insertProcessList = new ArrayList<>();
         List<ProcessCraftEntity> insertProcessCraftList = new ArrayList<>();
         if(CollectionUtil.isNotEmpty(dataList)){
             for (List<LinkedHashMap> mapList : dataList) {
                 LinkedHashMap linkedHashMap = mapList.get(0);
                 String processName = linkedHashMap.get("1").toString();
                 String processNum = linkedHashMap.get("3").toString();
                 String processDescription = linkedHashMap.get("5").toString();
                 //校验数据
                 List<ProcessEntity> processEntities = processMapper.selectList(new QueryWrapper<>());
                 if(CollectionUtil.isNotEmpty(processEntities)){
                     List<String> existProcessNums = processEntities
                             .stream()
                             .map(ProcessEntity::getProcessNum)
                             .collect(Collectors.toList());
                     if(existProcessNums.contains(processNum)){
                         return;
                     }
                 }
                 ProcessEntity processEntity = new ProcessEntity();
                 processEntity.setProcessNum(processNum);
                 processEntity.setName(processName);
                 processEntity.setDescription(processDescription);
                 String processCode = "process" + "-" + UUIDUtil.getUUID();
                 processEntity.setCode(processCode);
                 processEntity.setVersion(1);
                 processEntity.setCreateTime(new Date());
                 processEntity.setStatus(0);
                 insertProcessList.add(processEntity);
                 //操作工艺工序
                 if(mapList.size()>2){
                     for (int i = 2; i < mapList.size(); i++) {
                         LinkedHashMap linkedHashMap1 = mapList.get(i);
                         ProcessCraftEntity processCraftEntity = new ProcessCraftEntity();
                         processCraftEntity.setName(linkedHashMap1.get("1").toString());
                         processCraftEntity.setContent(linkedHashMap1.get("2").toString());
                         processCraftEntity.setCode("craft"+"-"+UUIDUtil.getUUID());
                         processCraftEntity.setVersion(1);
                         try{
                             processCraftEntity.setSeq(Integer.valueOf(linkedHashMap1.get("0").toString()));
                         }catch (Exception e){

                         }
                         processCraftEntity.setProcessCode(processCode);
                         processCraftEntity.setAdjust(Double.valueOf(linkedHashMap1.get("3").toString()));
                         processCraftEntity.setSingleTimeConsuming(new BigDecimal(linkedHashMap1.get("4").toString()));
                         insertProcessCraftList.add(processCraftEntity);
                     }
                 }
             }
         }
         //持久化
        if(CollectionUtil.isNotEmpty(insertProcessList)){
            insertProcessList = insertProcessList
                    .stream()
                    .filter(distinctByKey(ProcessEntity::getProcessNum))
                    .collect(Collectors.toList());
            processMapper.insertBatchSomeColumn(insertProcessList);
        }
        if(CollectionUtil.isNotEmpty(insertProcessCraftList)){
            processCraftMapper.insertBatchSomeColumn(insertProcessCraftList);
        }
    }

    static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    public Object confirmTask(Integer id, Integer confirmFlag) {
        machineToolTaskRespository.confirmTask(id , confirmFlag);
        return Boolean.TRUE;
    }

    @Transactional
    public void deleteTask(DeleteTaskReq deleteTaskReq) {
        machineToolTaskRespository.delete(deleteTaskReq.getId());
        QueryWrapper<OrderCraftEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id" , deleteTaskReq.getTaskId());
        OrderCraftEntity orderCraftEntity = orderCraftMapper.selectOne(wrapper);
        if(ObjectUtil.isNotNull(orderCraftEntity)){
            List<CraftParamVo> craftParamVoList = JSONArray.parseArray(orderCraftEntity.getCraftParam(), CraftParamVo.class).stream().
                    sorted(Comparator.comparingInt(CraftParamVo::getSeq)).
                    collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(craftParamVoList)){
                craftParamVoList.forEach(craftParamVo -> {
                    if (craftParamVo.getCode().equals(deleteTaskReq.getCraftCode())) {
                        //设置未分配数量
                        craftParamVo.setTypeFlag(0);
                        craftParamVo.setCraftUnallocatedNumber(craftParamVo.getCraftPlanNumber());
                    }
                });
                orderCraftEntity.setCraftParam(JSONArray.toJSONString(craftParamVoList));
                orderCraftMapper.updateById(orderCraftEntity);
            }
        }
    }

    public void changeCraftParams() {
        QueryWrapper<OrderCraftEntity> wrapper = new QueryWrapper<>();
        List<OrderCraftEntity> orderCraftEntities = orderCraftMapper.selectList(wrapper);
        List<OrderCraftEntity> updateList = new ArrayList<>();
        for (OrderCraftEntity orderCraftEntity : orderCraftEntities) {
            if(StringUtils.isNotBlank(orderCraftEntity.getCraftParam())){
               List<CraftParamVoReload> craftParamVos = JSONArray.parseArray(orderCraftEntity.getCraftParam() , CraftParamVoReload.class);
               if(CollectionUtil.isNotEmpty(craftParamVos)){
                   List<CraftParamVo> craftParamVoList = new ArrayList<>();
                   for (CraftParamVoReload craftParamVo : craftParamVos) {
                       CraftParamVo craftParamVo1 = new CraftParamVo();
                       BeanUtils.copyProperties(craftParamVo , craftParamVo1);
                       if(Objects.equals(craftParamVo.getCraftPlanNumber() , craftParamVo.getCraftUnallocatedNumber())){
                           craftParamVo1.setTypeFlag(0);
                       }else{
                           craftParamVo1.setTypeFlag(1);
                       }
                       craftParamVoList.add(craftParamVo1);
                   }
                   orderCraftEntity.setCraftParam(JSONArray.toJSONString(craftParamVoList));
                   updateList.add(orderCraftEntity);
               }
            }
        }
        if(CollectionUtil.isNotEmpty(updateList)){
            List<List<OrderCraftEntity>> lists = CommonUtil.groupList(updateList);
            for (List<OrderCraftEntity> list : lists) {
                orderCraftMapper.updateBatchById(list);
            }
            //orderCraftMapper.updateBatchById(updateList);
        }
    }
}
